package codeTop;

import java.io.StringBufferInputStream;
import java.util.ArrayList;
import java.util.List;

public class q22 {
    public List<String> generateParenthesis(int n) {
        dfs(n,0,0,new StringBuilder());
        return res;
    }
    List<String> res = new ArrayList<>();
    void dfs(int n,int left, int right, StringBuilder sb){
        if (left == n && right == n) {
            res.add(sb.toString());
            return;
        }
        if (left < n) {
            sb.append('(');
            dfs(n,left+1,right,sb);
            sb.deleteCharAt(sb.length()-1);
        }
        if (right < left) {
            sb.append(')');
            dfs(n,left,right+1,sb);
            sb.deleteCharAt(sb.length()-1);
        }
    }
}
